import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  message,
  Alert,
  Statistic,
  Row,
  Col,
  Modal,
  Typography,
  Progress,
  Badge,
  Tooltip,
  Tabs
} from 'antd';
import {
  ReloadOutlined,
  DownloadOutlined,
  HistoryOutlined,
  TrophyOutlined,
  CalendarOutlined,
  DatabaseOutlined,
  SyncOutlined,
  ApiOutlined,
  ToolOutlined,
  BarChartOutlined,
  BulbOutlined
} from '@ant-design/icons';
import DatabaseService from './database';
import LotteryApiService from './lotteryApi';
import LotteryDistribution from './LotteryDistribution';
import LotteryPrediction from './LotteryPrediction';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const LotteryHistory = ({ isMobile = false }) => {
  const [loading, setLoading] = useState(false);
  const [historyData, setHistoryData] = useState([]);
  const [activeTab, setActiveTab] = useState('history'); // 新增：当前激活的标签页
  const [statistics, setStatistics] = useState({
    total: 0,
    lastUpdate: null,
    apiStatus: 'unknown'
  });
  const [syncProgress, setSyncProgress] = useState({
    visible: false,
    current: 0,
    total: 0,
    status: 'normal'
  });

  // 初始化加载数据
  useEffect(() => {
    loadHistoryFromDatabase();
    checkApiStatus();
    
    // 添加调试信息
    console.log('LotteryHistory组件已挂载');
  }, []);

  // 数据库健康检查
  const healthCheck = async () => {
    try {
      setLoading(true);
      console.log('=== 开始数据库健康检查 ===');
      
      const result = await DatabaseService.healthCheck();
      
      if (result.isConnected) {
        message.success(`数据库连接正常！记录数: ${result.recordCount}`);
      } else {
        message.error('数据库连接失败');
      }
      
      console.log('健康检查结果:', result);
      
    } catch (error) {
      console.error('健康检查失败:', error);
      message.error('健康检查失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 重置数据库
  const resetDatabase = async () => {
    try {
      setLoading(true);
      console.log('=== 开始重置数据库 ===');
      
      await DatabaseService.resetDatabase();
      
      // 重新加载数据
        await loadHistoryFromDatabase();
      
      message.success('数据库重置成功！');
      
    } catch (error) {
      console.error('重置数据库失败:', error);
      message.error('重置失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据库（添加示例数据）
  const initializeDatabase = async () => {
    try {
      setLoading(true);
      console.log('=== 开始初始化数据库 ===');
      
      const result = await DatabaseService.initializeDatabase();
      
      if (result) {
         // 重新加载数据
          await loadHistoryFromDatabase();
         message.success('数据库初始化成功，已添加示例数据！');
      } else {
        message.info('数据库已有数据，无需初始化');
      }
      
    } catch (error) {
      console.error('初始化数据库失败:', error);
      message.error('初始化失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 网络诊断功能
  const diagnoseNetwork = async () => {
    try {
      setLoading(true);
      console.log('=== 开始网络诊断 ===');
      
      // 获取环境信息
      const envInfo = LotteryApiService.getEnvironmentInfo();
      console.log('环境信息:', envInfo);
      
      // 诊断结果
      const diagnostics = {
        environment: envInfo,
        networkTests: [],
        recommendations: []
      };
      
      // 测试1: 基础网络连接
      diagnostics.networkTests.push({
        name: '基础网络连接',
        status: navigator.onLine ? 'pass' : 'fail',
        message: navigator.onLine ? '网络连接正常' : '设备离线，请检查网络连接'
      });
      
      // 测试2: 环境检测
      diagnostics.networkTests.push({
        name: '运行环境',
        status: envInfo.isTauri ? 'pass' : 'warning',
        message: envInfo.isTauri ? 'Tauri环境' : '浏览器环境（可能需要代理）'
      });
      
      // 测试3: 安卓环境检测
      if (envInfo.isAndroid) {
        diagnostics.networkTests.push({
          name: '安卓环境',
          status: 'warning',
          message: '安卓环境检测到，可能需要特殊网络配置'
        });
        
        diagnostics.recommendations.push('运行网络修复脚本: npm run android:fix-network');
        diagnostics.recommendations.push('确保应用有网络权限');
        diagnostics.recommendations.push('检查安卓网络安全策略配置');
      }
      
      // 测试4: API连接测试
      try {
        const apiTest = await fetch(envInfo.isTauri ? 'https://api.jisuapi.com' : '/caipiao', {
          method: 'HEAD',
          mode: 'no-cors',
          signal: AbortSignal.timeout(5000)
        });
        
        diagnostics.networkTests.push({
          name: 'API服务器连接',
          status: 'pass',
          message: 'API服务器可达'
        });
      } catch (apiError) {
        diagnostics.networkTests.push({
          name: 'API服务器连接',
          status: 'fail',
          message: `API连接失败: ${apiError.message}`
        });
        
        if (envInfo.isAndroid) {
          diagnostics.recommendations.push('在安卓环境中，API连接可能被网络安全策略阻止');
          diagnostics.recommendations.push('尝试使用模拟数据进行演示');
        }
      }
      
      // 生成建议
      if (!envInfo.isTauri && !envInfo.isAndroid) {
        diagnostics.recommendations.push('在浏览器环境中，确保代理配置正确');
      }
      
      if (diagnostics.networkTests.some(test => test.status === 'fail')) {
        diagnostics.recommendations.push('考虑使用模拟数据进行功能演示');
      }
      
      // 显示诊断结果
      Modal.info({
        title: '网络诊断报告',
        width: 800,
        content: (
          <div>
            <h4>环境信息</h4>
            <ul>
              <li><strong>运行环境:</strong> {envInfo.isTauri ? 'Tauri应用' : '浏览器'}</li>
              <li><strong>操作系统:</strong> {envInfo.isAndroid ? 'Android' : '其他'}</li>
              <li><strong>网络状态:</strong> {envInfo.isOnline ? '在线' : '离线'}</li>
              <li><strong>协议:</strong> {envInfo.protocol}</li>
              <li><strong>主机:</strong> {envInfo.host}</li>
            </ul>
            
            <h4>网络测试结果</h4>
            {diagnostics.networkTests.map((test, index) => (
              <div key={index} style={{ marginBottom: '8px' }}>
                <span style={{ 
                  color: test.status === 'pass' ? '#52c41a' : test.status === 'fail' ? '#ff4d4f' : '#faad14',
                  marginRight: '8px'
                }}>
                  {test.status === 'pass' ? '✓' : test.status === 'fail' ? '✗' : '⚠'}
                </span>
                <strong>{test.name}:</strong> {test.message}
              </div>
            ))}
            
            {diagnostics.recommendations.length > 0 && (
              <>
                <h4>建议解决方案</h4>
                <ul>
                  {diagnostics.recommendations.map((rec, index) => (
                    <li key={index}>{rec}</li>
                  ))}
                </ul>
              </>
            )}
            
            <h4>详细信息</h4>
            <pre style={{
              maxHeight: '200px', 
              overflow: 'auto', 
              background: '#f5f5f5', 
              padding: '10px',
              fontSize: '12px'
            }}>
              {JSON.stringify(diagnostics, null, 2)}
            </pre>
          </div>
        )
      });
      
      message.info('网络诊断完成，请查看详细报告');
      
    } catch (error) {
      console.error('网络诊断失败:', error);
      message.error('网络诊断失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 测试API响应
  const testApiResponse = async () => {
    try {
      setLoading(true);
      console.log('=== 开始测试API响应 ===');
      
      // 设置全局Modal引用
      window.Modal = Modal;
      
      message.info('正在测试API，请查看弹窗了解详细响应信息...');
      
      // 测试获取历史记录API
      const result = await LotteryApiService.getLotteryHistory(0, 5, true);
      console.log('API测试结果:', result);
      
      if (result.success) {
        message.success('API测试成功！请查看弹窗了解详细信息');
      } else {
        message.error(`API测试失败: ${result.error}`);
      }
      
    } catch (error) {
      console.error('测试API失败:', error);
      message.error('测试API失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };



  // 从数据库加载历史记录
  const loadHistoryFromDatabase = async () => {
    try {
      setLoading(true);
      console.log('开始加载历史记录...');
      
      const records = await DatabaseService.getAllLotteryHistory();
      console.log('从数据库获取到的记录:', records);
      
      // 确保记录按日期从新到旧排序
      const sortedRecords = records.sort((a, b) => {
        const getDate = (record) => {
          if (record.opendatetime) {
            return new Date(record.opendatetime);
          } else if (record.opendate) {
            return new Date(record.opendate);
          } else if (record.createTime) {
            return new Date(record.createTime);
          }
          return new Date(0);
        };
        
        const dateA = getDate(a);
        const dateB = getDate(b);
        return dateB - dateA; // 降序排列，最新的在前
      });
      
      setHistoryData(sortedRecords);
      
      const count = await DatabaseService.getLotteryHistoryCount();
      console.log('记录总数:', count);
      
      setStatistics(prev => ({
        ...prev,
        total: count,
        lastUpdate: sortedRecords.length > 0 ? (sortedRecords[0].createTime || sortedRecords[0].opendate) : null
      }));
      
      if (sortedRecords.length === 0) {
        console.log('数据库中没有历史记录');
        message.info('暂无历史记录，请点击"同步数据"获取开奖信息');
      } else {
        console.log(`成功加载 ${sortedRecords.length} 条历史记录，已按日期从新到旧排序`);
      }
    } catch (error) {
      console.error('加载历史记录失败:', error);
      message.error(`加载历史记录失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 检查API状态
  const checkApiStatus = () => {
    const isConfigured = LotteryApiService.isApiKeyConfigured();
    setStatistics(prev => ({
      ...prev,
      apiStatus: isConfigured ? 'configured' : 'not_configured'
    }));
  };

  // 同步历史记录
  const syncHistoryData = async () => {
    try {
      setLoading(true);
      setSyncProgress({
        visible: true,
        current: 0,
        total: 100,
        status: 'active'
      });

      let newRecords = [];
      let addedCount = 0;

      // 检查是否配置了API密钥
      if (!LotteryApiService.isApiKeyConfigured()) {
        // 使用模拟数据
        console.log('API密钥未配置，使用模拟数据');
        message.info('API密钥未配置，使用模拟数据进行演示');
        setSyncProgress(prev => ({ ...prev, current: 30 }));
        
        const mockData = LotteryApiService.getMockData();
        console.log('获取到模拟数据:', mockData);
        setSyncProgress(prev => ({ ...prev, current: 60 }));
        
        // 显示模拟数据弹窗
        Modal.info({
          title: '使用模拟数据',
          content: (
            <div>
              <p><strong>数据来源:</strong> 本地模拟数据</p>
              <p><strong>记录数量:</strong> {mockData.length} 条</p>
              <p><strong>数据预览:</strong></p>
              <pre style={{maxHeight: '300px', overflow: 'auto', background: '#f5f5f5', padding: '10px'}}>
                {JSON.stringify(mockData.slice(0, 2), null, 2)}
              </pre>
            </div>
          ),
          width: 800
        });
        
        // 保存模拟数据到数据库
        for (let i = 0; i < mockData.length; i++) {
          const record = mockData[i];
          console.log(`正在保存第 ${i + 1} 条记录:`, record);
          
          try {
            const savedRecord = await DatabaseService.addLotteryHistory(record);
            if (savedRecord) {
              addedCount++;
              console.log(`成功保存记录 ${record.issueno}`);
            }
          } catch (saveError) {
            console.error(`保存记录 ${record.issueno} 失败:`, saveError);
          }
          
          setSyncProgress(prev => ({ 
            ...prev, 
            current: 60 + (i + 1) / mockData.length * 30 
          }));
        }
        
        newRecords = mockData;
      } else {
        // 使用真实API
        console.log('使用真实API获取数据');
        message.info('正在从API获取数据，请查看弹窗了解详细信息...');
        setSyncProgress(prev => ({ ...prev, current: 20 }));
        
        // 设置全局Modal引用，让API服务可以显示弹窗
        window.Modal = Modal;
        
        const result = await LotteryApiService.getRecentMonthHistory(true); // 启用弹窗显示
        console.log('API返回结果:', result);
        setSyncProgress(prev => ({ ...prev, current: 60 }));
        
        if (result.success) {
          // 保存到数据库
          for (let i = 0; i < result.data.length; i++) {
            const record = result.data[i];
            console.log(`正在保存第 ${i + 1} 条记录:`, record);
            
            try {
              const savedRecord = await DatabaseService.addLotteryHistory(record);
              if (savedRecord) {
                addedCount++;
                console.log(`成功保存记录 ${record.issueno}`);
              }
            } catch (saveError) {
              console.error(`保存记录 ${record.issueno} 失败:`, saveError);
            }
            
            setSyncProgress(prev => ({ 
              ...prev, 
              current: 60 + (i + 1) / result.data.length * 30 
            }));
          }
          newRecords = result.data;
        } else {
          throw new Error(result.error);
        }
      }

      setSyncProgress(prev => ({ ...prev, current: 100, status: 'success' }));
      
      console.log(`同步完成，总共处理 ${newRecords.length} 条记录，实际新增 ${addedCount} 条`);
      
      // 清理旧记录，保持最多36条
      try {
        const cleanupResult = await DatabaseService.cleanupOldRecords();
        if (cleanupResult.cleaned > 0) {
          console.log(`自动清理了 ${cleanupResult.cleaned} 条旧记录，当前保留 ${cleanupResult.remaining} 条记录`);
        }
      } catch (cleanupError) {
        console.error('清理旧记录失败:', cleanupError);
      }
      
      // 重新加载数据
      await loadHistoryFromDatabase();
      
      if (addedCount > 0) {
        message.success(`同步完成！新增 ${addedCount} 条记录`);
      } else {
        message.info('同步完成！没有新的记录需要添加');
      }
      
    } catch (error) {
      console.error('同步历史记录失败:', error);
      message.error(`同步失败: ${error.message}`);
      setSyncProgress(prev => ({ ...prev, status: 'exception' }));
    } finally {
      setLoading(false);
      setTimeout(() => {
        setSyncProgress(prev => ({ ...prev, visible: false }));
      }, 2000);
    }
  };

  // 清空历史记录
  const clearHistory = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空所有历史记录吗？此操作不可恢复。',
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await DatabaseService.clearAllLotteryHistory();
          await loadHistoryFromDatabase();
          message.success('历史记录已清空');
        } catch (error) {
          console.error('清空历史记录失败:', error);
          message.error('清空失败');
        }
      }
    });
  };

  // 格式化开奖号码显示
  const formatNumbers = (number, refernumber) => {
    const redBalls = number.split(' ');
    return (
      <Space size="small" wrap>
        {redBalls.map((ball, index) => (
          <Tag key={index} color="red" style={{ 
            minWidth: isMobile ? '24px' : '28px', 
            textAlign: 'center',
            fontSize: isMobile ? '12px' : '14px'
          }}>
            {ball}
          </Tag>
        ))}
        <Tag color="blue" style={{ 
          minWidth: isMobile ? '24px' : '28px', 
          textAlign: 'center',
          fontSize: isMobile ? '12px' : '14px'
        }}>
          {refernumber}
        </Tag>
      </Space>
    );
  };

  // 格式化奖金
  const formatMoney = (amount) => {
    if (!amount) return '-';
    const num = parseInt(amount);
    if (num >= 100000000) {
      return `${(num / 100000000).toFixed(1)}亿`;
    } else if (num >= 10000) {
      return `${(num / 10000).toFixed(1)}万`;
    }
    return num.toLocaleString();
  };

  // 格式化开奖时间
  const formatDateTime = (record) => {
    if (record.opendatetime) {
      const dateTime = new Date(record.opendatetime);
      return (
        <div style={{ fontSize: isMobile ? '12px' : '14px' }}>
          <div>{dateTime.toLocaleDateString('zh-CN')}</div>
          <div style={{ color: '#666', fontSize: isMobile ? '11px' : '12px' }}>
            {dateTime.toLocaleTimeString('zh-CN', { hour12: false })}
          </div>
        </div>
      );
    } else if (record.opendate && record.opentime) {
      return (
        <div style={{ fontSize: isMobile ? '12px' : '14px' }}>
          <div>{record.opendate}</div>
          <div style={{ color: '#666', fontSize: isMobile ? '11px' : '12px' }}>
            {record.opentime}
          </div>
        </div>
      );
    } else {
      return (
        <Text style={{ fontSize: isMobile ? '12px' : '14px' }}>
          {record.opendate || '-'}
        </Text>
      );
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '期号',
      dataIndex: 'issueno',
      key: 'issueno',
      width: isMobile ? 80 : 100,
      fixed: isMobile ? 'left' : false,
      render: (text) => (
        <Text strong style={{ fontSize: isMobile ? '12px' : '14px' }}>
          {text}
        </Text>
      )
    },
    {
      title: '开奖号码',
      key: 'numbers',
      width: isMobile ? 180 : 260,
      render: (_, record) => formatNumbers(record.number, record.refernumber)
    },
    {
      title: '开奖时间',
      key: 'datetime',
      width: isMobile ? 100 : 130,
      sorter: (a, b) => {
        // 获取日期进行比较，优先使用 opendatetime，然后是 opendate
        const getDate = (record) => {
          if (record.opendatetime) {
            return new Date(record.opendatetime);
          } else if (record.opendate) {
            return new Date(record.opendate);
          } else if (record.createTime) {
            return new Date(record.createTime);
          }
          return new Date(0); // 默认最早日期
        };
        
        const dateA = getDate(a);
        const dateB = getDate(b);
        return dateB - dateA; // 降序排列，最新的在前
      },
      defaultSortOrder: 'ascend', // 设置默认排序为升序（因为sorter已经是降序逻辑）
      render: (_, record) => formatDateTime(record)
    },
    ...(isMobile ? [] : [
      {
        title: '销售额',
        dataIndex: 'saleamount',
        key: 'saleamount',
        width: 100,
        render: (amount) => (
          <Text style={{ fontSize: '12px' }}>
            {formatMoney(amount)}
          </Text>
        )
      },
      {
        title: '奖池奖金',
        dataIndex: 'totalmoney',
        key: 'totalmoney',
        width: 100,
        render: (amount) => (
          <Text style={{ fontSize: '12px' }}>
            {formatMoney(amount)}
          </Text>
        )
      },
      {
        title: '一等奖',
        key: 'firstPrize',
        width: 120,
        render: (_, record) => {
          const firstPrize = record.prize?.find(p => p.prizename === '一等奖');
          if (!firstPrize) return '-';
          return (
            <div style={{ fontSize: '12px' }}>
              <div>{firstPrize.num}注</div>
              <div>{formatMoney(firstPrize.singlebonus)}</div>
            </div>
          );
        }
      }
    ])
  ];

  return (
    <div style={{ padding: isMobile ? '8px' : '16px' }}>
      {/* 页面标题和统计信息 */}
      <Card 
        className={isMobile ? 'mobile-card' : ''}
        style={{ marginBottom: isMobile ? 12 : 16 }}
      >
        <Row gutter={[16, 16]} align="middle">
          <Col flex="auto">
            <Title level={isMobile ? 4 : 3} style={{ margin: 0 }}>
              <HistoryOutlined style={{ marginRight: 8 }} />
              双色球历史记录
            </Title>
          </Col>
          <Col>
            <Space size={isMobile ? 'small' : 'middle'}>
              <Button
                type="primary"
                icon={<SyncOutlined />}
                onClick={syncHistoryData}
                loading={loading}
                size={isMobile ? 'small' : 'middle'}
              >
                {isMobile ? '同步' : '同步数据'}
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={loadHistoryFromDatabase}
                size={isMobile ? 'small' : 'middle'}
              >
                刷新
              </Button>
              <Button
                 icon={<DatabaseOutlined />}
                 onClick={healthCheck}
                 size={isMobile ? 'small' : 'middle'}
                 type="dashed"
               >
                 检查
               </Button>
               <Button
                 icon={<ApiOutlined />}
                 onClick={testApiResponse}
                 size={isMobile ? 'small' : 'middle'}
                 type="primary"
                 ghost
               >
                 测试API
               </Button>
               <Button
                 icon={<ToolOutlined />}
                 onClick={diagnoseNetwork}
                 size={isMobile ? 'small' : 'middle'}
                 type="default"
               >
                 {isMobile ? '诊断' : '网络诊断'}
               </Button>
               {!isMobile && (
                 <>
                   <Button
                     icon={<DatabaseOutlined />}
                     onClick={initializeDatabase}
                     size="middle"
                     type="default"
                   >
                     初始化
                   </Button>
                   <Button
                     danger
                     icon={<DatabaseOutlined />}
                     onClick={clearHistory}
                     size="middle"
                   >
                     清空
                   </Button>
                 </>
               )}
            </Space>
          </Col>
        </Row>

        {/* 统计信息 */}
        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col span={isMobile ? 8 : 6}>
            <Statistic
              title="记录总数"
              value={statistics.total}
              prefix={<DatabaseOutlined />}
              valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
            />
          </Col>
          <Col span={isMobile ? 8 : 6}>
            <Statistic
              title="API状态"
              value={statistics.apiStatus === 'configured' ? '已配置' : '未配置'}
              prefix={<Badge 
                status={statistics.apiStatus === 'configured' ? 'success' : 'warning'} 
              />}
              valueStyle={{ 
                fontSize: isMobile ? '14px' : '16px',
                color: statistics.apiStatus === 'configured' ? '#52c41a' : '#faad14'
              }}
            />
          </Col>
          <Col span={isMobile ? 8 : 12}>
            <Statistic
              title="最后更新"
              value={statistics.lastUpdate ? 
                new Date(statistics.lastUpdate).toLocaleString() : '暂无数据'}
              prefix={<CalendarOutlined />}
              valueStyle={{ fontSize: isMobile ? '12px' : '14px' }}
            />
          </Col>
        </Row>
      </Card>

      {/* API状态提示 */}
      {statistics.apiStatus === 'not_configured' && (
        <Alert
          message="API密钥未配置"
          description={
            <div>
              <p>当前使用模拟数据进行演示。要获取真实的开奖数据，请：</p>
              <ol style={{ marginLeft: 20, marginTop: 8 }}>
                <li>访问极速数据官网注册账号</li>
                <li>申请彩票开奖API接口</li>
                <li>在 lotteryApi.js 文件中配置您的API密钥</li>
              </ol>
            </div>
          }
          type="warning"
          showIcon
          style={{ marginBottom: isMobile ? 12 : 16 }}
          action={
            <Button size="small" type="link" href="https://www.jisuapi.com/api/caipiao/" target="_blank">
              申请API
            </Button>
          }
        />
      )}

      {/* 同步进度 */}
      {syncProgress.visible && (
        <Card style={{ marginBottom: isMobile ? 12 : 16 }}>
          <div style={{ textAlign: 'center' }}>
            <Title level={5}>正在同步历史数据...</Title>
            <Progress
              percent={Math.round(syncProgress.current)}
              status={syncProgress.status}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        </Card>
      )}

      {/* 标签页内容 */}
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        size={isMobile ? 'small' : 'default'}
        items={[
           {
             key: 'history',
             label: (
               <span>
                 <TrophyOutlined />
                 {!isMobile && ' 开奖记录'}
               </span>
             ),
             children: (
               <Card 
                 title={
                   <Space>
                     <TrophyOutlined />
                     <span>开奖记录</span>
                     <Badge count={historyData.length} showZero />
                   </Space>
                 }
                 className={isMobile ? 'mobile-card' : ''}
                 extra={
                   !isMobile && (
                     <Tooltip title="导出数据">
                       <Button 
                         icon={<DownloadOutlined />} 
                         size="small"
                         onClick={() => message.info('导出功能开发中...')}
                       >
                         导出
                       </Button>
                     </Tooltip>
                   )
                 }
               >
                 <Table
                   columns={columns}
                   dataSource={historyData}
                   rowKey="id"
                   loading={loading}
                   size={isMobile ? 'small' : 'middle'}
                   scroll={isMobile ? { x: 600 } : undefined}
                   defaultSortOrder="ascend"
                   sortDirections={['ascend', 'descend']}
                   showSorterTooltip={{
                     title: '点击排序'
                   }}
                   pagination={{
                     pageSize: isMobile ? 20 : 36,
                     showSizeChanger: !isMobile,
                     showQuickJumper: false,
                     showTotal: (total, range) => 
                       `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录 (最多显示36条最新记录)`,
                     ...(isMobile ? { simple: true } : {}),
                     hideOnSinglePage: true
                   }}
                   locale={{
                     emptyText: (
                       <div style={{ padding: '40px 0', textAlign: 'center' }}>
                         <HistoryOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                         <div style={{ marginTop: 16, color: '#999' }}>
                           暂无历史记录
                         </div>
                         <Button 
                           type="primary" 
                           style={{ marginTop: 16 }}
                           onClick={syncHistoryData}
                           loading={loading}
                         >
                           立即同步数据
                         </Button>
                       </div>
                     )
                   }}
                 />
               </Card>
             )
           },
           {
             key: 'distribution',
             label: (
               <span>
                 <BarChartOutlined />
                 {!isMobile && ' 分布图'}
               </span>
             ),
             children: (
               <LotteryDistribution 
                 historyData={historyData} 
                 isMobile={isMobile}
               />
             )
           },
           {
             key: 'prediction',
             label: (
               <span>
                 <BulbOutlined />
                 {!isMobile && ' 智能预测'}
               </span>
             ),
             children: (
               <LotteryPrediction 
                 historyData={historyData} 
                 isMobile={isMobile}
               />
             )
           }
         ]}
      />

      {/* 移动端额外操作 */}
      {isMobile && historyData.length > 0 && (
        <Card style={{ marginTop: 12 }}>
          <Space style={{ width: '100%', justifyContent: 'center' }} wrap>
            <Button 
              icon={<ApiOutlined />} 
              onClick={testApiResponse}
              size="small"
              type="primary"
              ghost
            >
              测试API
            </Button>
            <Button 
              icon={<DatabaseOutlined />} 
              onClick={initializeDatabase}
              size="small"
            >
              初始化
            </Button>
            <Button 
              danger 
              icon={<DatabaseOutlined />} 
              onClick={clearHistory}
              size="small"
            >
              清空记录
            </Button>
            <Button 
              icon={<DownloadOutlined />} 
              onClick={() => message.info('导出功能开发中...')}
              size="small"
            >
              导出数据
            </Button>
          </Space>
        </Card>
      )}
    </div>
  );
};

export default LotteryHistory;